package com.example.menuvirtualclient.repository;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.nsd.NsdManager.DiscoveryListener;
import android.util.Log;

import com.example.menuvirtualclient.core.*;
import com.example.menuvirtualclient.data.Repository;
import com.example.menuvirtualclient.util.Common;

public class DishRepository extends Repository<Dish> {

	private static final String LOGTAG = "DishRepository";
	
	public DishRepository(Context context) {
		super(context);
	}
	
	public List<Dish> GetDishesByMenu(int menuId) {
		SQLiteDatabase db = null;
		try{
			List<Dish> list = new ArrayList<Dish>();
			String[] filter = new String[1];
			filter[0] = Long.toString(menuId);
			
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();
			Cursor cursor = db.rawQuery("SELECT d.id, d.name, d.description, d.photo, d.status, d.celiac, d.cookingpoint, d.day, d.hourfrom, d.hourto, d.value, d.size FROM Dishes_Menues dm INNER JOIN Dishes d ON d.id = dm.dishid WHERE dm.menuid = ? ", filter);
			
			cursor.moveToFirst();
		    while (!cursor.isAfterLast()) {
		    	list.add(BuildNewEntity(cursor));
		    	cursor.moveToNext();
		    }
		    cursor.close();
		    db.close();
		    return list;
		}
		catch(SQLiteException ex){
			Log.e(LOGTAG, ex.getMessage());
			throw ex;
		}		
		finally{
			if(db != null)
				if(db.isOpen()) db.close();
		}
	}
	
	@Override
	public Dish Get(long id) {
		SQLiteDatabase db = null;
		Dish entity = null;
		String[] filter = new String[1];
		filter[0] = Long.toString(id);
		try{
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();			
			Cursor cursor = db.rawQuery("SELECT id, name, description, photo, status, celiac, cookingpoint, day, hourfrom, hourto, value, size FROM Dishes WHERE id = ?", filter);
			
			cursor.moveToFirst();
			entity = BuildNewEntity(cursor); 
			cursor.close();
		    db.close();
		}
		catch(Exception ex){
			Log.e(LOGTAG, ex.getMessage());			
		}
		finally{
			if(db != null)
				if(db.isOpen()) {
					db.close();
					Log.e(LOGTAG, "Close database");		
				}
		}
		return entity;
	}
	
	@Override
	public void Insert(Dish entity) {
		SQLiteDatabase db = null;
		try{
			ContentValues newRow = new ContentValues();
			newRow.put("id", entity.getId());			
			newRow.put("name", entity.getName());
			newRow.put("description", entity.getDescription());
			newRow.put("photo", entity.getPhoto());
			newRow.put("status", entity.getStatus());
			newRow.put("celiac", entity.getCeliac());
			newRow.put("cookingpoint", entity.getCookingPoint());
			newRow.put("size", entity.getSize());
			newRow.put("day", entity.getDay());
			newRow.put("hourfrom", entity.getHourFrom());
			newRow.put("hourto", entity.getHourTo());
			newRow.put("value", entity.getPrice());
			
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();
			db.insert(getTableName(), null, newRow);
			
			db.close();
		}
		catch(NullPointerException ex){
			Log.e(LOGTAG, ex.getMessage());
		}
		catch(SQLiteException ex){
			Log.e(LOGTAG, ex.getMessage());
		}
		catch(Exception ex){
			Log.e(LOGTAG, ex.getMessage());		
		}
		finally{
			if(db != null)
				if(db.isOpen()) db.close();
			_session.Close();
		}
	}
	
	public List<Comment> GetCommnetsByDish(int dishId) {
		SQLiteDatabase db = null;
		try{
			List<Comment> list = new ArrayList<Comment>();
			String[] filter = new String[1];
			filter[0] = Long.toString(dishId);
			
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();
			Cursor cursor = db.rawQuery("SELECT c.id, c.description, c.price FROM Dishes_Comments dc INNER JOIN Comments c ON c.id = dc.commentid WHERE dc.dishid = ? ", filter);
			
			cursor.moveToFirst();
		    while (!cursor.isAfterLast()) {
		    	Comment comment = new Comment();
		    	comment.setId(cursor.getInt(0));
		    	comment.setDescription(cursor.getString(1));
		    	double price = Common.Round(cursor.getDouble(2), 2); 
				comment.setPrice(price);
		    	
		    	list.add(comment);
		    	cursor.moveToNext();
		    }
		    cursor.close();
		    db.close();
		    return list;
		}
		catch(SQLiteException ex){
			Log.e(LOGTAG, ex.getMessage());
			throw ex;
		}		
		finally{
			if(db != null)
				if(db.isOpen()) db.close();
		}
	}
	
	
	public void saveDishComment(DishComment entity) {
		SQLiteDatabase db = null;
		try{
			ContentValues newRow = new ContentValues();
			newRow.put("dishid", entity.getDishId());			
			newRow.put("commentid", entity.getCommentId());			
			
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();
			db.insert("Dishes_Comments", null, newRow);
			
			db.close();
		}		
		catch(SQLiteException ex){
			Log.e(LOGTAG, ex.getMessage());
		}
		catch(Exception ex){
			Log.e(LOGTAG, ex.getMessage());		
		}
		finally{
			if(db != null)
				if(db.isOpen()) db.close();
			_session.Close();
		}
	}
	
	public boolean exist(DishComment entity) {
		SQLiteDatabase db = null;
		try{
			List<DishComment> list = new ArrayList<DishComment>();
			String[] filter = new String[2];
			filter[0] = Integer.toString(entity.getDishId());
			filter[1] = Integer.toString(entity.getCommentId());
			if(!_session.IsOpen())
				_session.Open();
			
			db = _session.Connection();
			Cursor cursor = db.rawQuery("SELECT dishid, commentid FROM Dishes_Comments WHERE dishid = ? AND commentid = ? ", filter);
			
			cursor.moveToFirst();
		    while (!cursor.isAfterLast()) {
		    	DishComment dishComment = new DishComment();
		    	dishComment.setDishId(cursor.getInt(0));
		    	dishComment.setCommentId(cursor.getInt(1));
		    	
		    	list.add(dishComment);
		    	cursor.moveToNext();
		    }
		    cursor.close();
		    db.close();
		    if(list != null && list.size() > 0)
		    	return true;
		    else
		    	return false;
		}
		catch(SQLiteException ex){
			Log.e(LOGTAG, ex.getMessage());
			throw ex;
		}		
		finally{
			if(db != null)
				if(db.isOpen()) db.close();
		}
	}
	
	@Override
	public String getTableName() {
		return "Dishes";
	}
	
	@Override
	public Dish BuildNewEntity(Cursor cursor) {
		Dish dish = new Dish();
		dish.setId(cursor.getInt(0));
		dish.setName(cursor.getString(1));
		dish.setDescription(cursor.getString(2));
		dish.setPhoto(cursor.getString(3));
		dish.setStatus(cursor.getInt(4));
		dish.setCeliac(cursor.getInt(5));
		dish.setCookingPoint(cursor.getInt(6));
		dish.setDay(cursor.getInt(7));
		dish.setHourFrom(cursor.getInt(8));
		dish.setHourTo(cursor.getInt(9));
		double price = Common.Round(cursor.getDouble(10), 2); 
		dish.setPrice(price);
		dish.setSize(cursor.getString(11));

		return dish;
	}
}
